import React, { FC } from 'react'
import Link from 'next/link'
import dayjs from 'dayjs'
import PostType from '@/types/post'

export type PostsProps = {
  posts: PostType[]
}

const PostsGroupByYear: FC<PostsProps> = ({ posts }) => {
  const allYears: number[] = []
  const postsGroupByYear: { [key: string]: PostType[] } = {}

  posts.forEach((post) => {
    const year = dayjs(post.date).year()
    if (!allYears.includes(year)) {
      allYears.push(year)
      postsGroupByYear[year] = [post]
    } else {
      postsGroupByYear[year].push(post)
    }
  })

  return (
    <ol className="space-y-8">
      {allYears.map((year) => (
        <li key={year} className="text-lg">
          <header className="mb-4 text-green-500">{year}年</header>
          <ol className="space-y-2">
            {postsGroupByYear[year].map(({ title, slug }) => (
              <li key={slug}>
                <Link href={`/posts/${slug}`}>
                  <a>{title}</a>
                </Link>
              </li>
            ))}
          </ol>
        </li>
      ))}
    </ol>
  )
}

export default PostsGroupByYear
